package org.hawk.gwt.ppc.reflect;

import java.io.FileReader;
import java.io.IOException;

import junit.framework.TestCase;

import org.hawk.gwt.ppc.Environment;
import org.hawk.gwt.ppc.ProcessingUnitsManager;
import org.hawk.gwt.ppc.parser.CompilationUnitDescriptor;
import org.hawk.gwt.ppc.parser.Token;
import org.hawk.gwt.ppc.utils.IO;
import org.hawk.gwt.ppc.utils.PreprocessorException;

public class ClassDelegateBuilderTestCase extends TestCase {
	private static final String MOCK05 = "org.hawk.gwt.ppc.reflect.mock.Mock5";
	private static final String MOCK05_PROCESSED = "./src/org/hawk/gwt/ppc/reflect/lang/mock/Mock1.java";
	private static final String MOCK06 = "org.hawk.gwt.ppc.reflect.mock.Mock6";
	private static final String MOCK06_PROCESSED = "./src/org/hawk/gwt/ppc/reflect/lang/mock/Mock2.java";
	private static final String MOCK07 = "org.hawk.gwt.ppc.reflect.mock.Mock7";
	private static final String MOCK07_PROCESSED = "./src/org/hawk/gwt/ppc/reflect/lang/mock/Mock3.java";
	
	@Override
	protected void setUp() throws Exception {
		super.setUp();
		ProcessingUnitsManager.getInstance().configure();
	}
	
	public void testBuildClassDelegate() throws PreprocessorException, IOException {
		assertEquals(getMock(MOCK05_PROCESSED), scan(MOCK05));
		assertEquals(getMock(MOCK06_PROCESSED), scan(MOCK06));
		assertEquals(getMock(MOCK07_PROCESSED), scan(MOCK07));
	}
	
	private String scan(String mock) throws PreprocessorException {
		StringBuilder stream = new StringBuilder();
		MetadataProcessor processor = new MetadataProcessor();
		processor.configure(Environment.getInstance().getConfiguration(), ProcessingUnitsManager.getInstance());
		processor.processCompilationUnit(mock);
		
		CompilationUnitDescriptor cu = ProcessingUnitsManager.getInstance().getRepository().findCompilationUnit(mock);
		Token tok = cu.getFirstToken();
		while (tok != null) {
			stream.append(tok.getRaw());
			tok = tok.next();
		}
		return stream.toString().replaceAll("\r", "");
	}
	
	private String getMock(String mock) throws IOException{
		return IO.toString(new FileReader(mock))
			.replaceAll("org.hawk.gwt.ppc.reflect.lang.mock", "org.hawk.gwt.ppc.reflect.mock")
			.replaceAll("Mock1", "Mock5")
			.replaceAll("Mock2", "Mock6")
			.replaceAll("Mock3", "Mock7")
			.replaceAll("\r", "");
	}
}
